package book.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class MessageDigestTest {

	private static final String HEX_NUMS_STR="0123456789abcdef";
	
	public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {

		//md2、md5、sha、sha-1、sha-256、sha384、sha512
		MessageDigest digest = MessageDigest.getInstance("sha-512");
		System.out.println("算法长度：" + digest.getDigestLength());
		System.out.println("算法名称：" + digest.getAlgorithm());
		System.out.println("算法provider：" + digest.getProvider());
		System.out.println("算法tostring：" + digest.toString());
		
		byte[] digested = digest.digest("tuyou".getBytes());
		byte[] digested3 = digest.digest("tuyou2".getBytes());

		System.out.println(toString(digested));
		System.out.println(toString(digested3));
		
		byte[] digested4 = hexStringToByte(toString(digested));
		System.out.println(Arrays.equals(digested, digested4));
	}

	public static String toString(byte[] digested) {

		StringBuilder sb = new StringBuilder();
		for (byte b : digested) {
			String item = Integer.toHexString(b & 0xff);
			if (item.length() == 1) {
				item = "0" + item;
			}
			sb.append(item);
		}
		return sb.toString();
	}

	public static byte[] hexStringToByte(String hex) {
		int len = (hex.length() / 2);
		byte[] result = new byte[len];
		char[] hexChars = hex.toCharArray();
		for (int i = 0; i < len; i++) {
			int pos = i * 2;
			result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
		}
		return result;
	}
}
